<script>
	import IM from "./lib/IMServer.js";
	import Vue from "vue";
	let _this;
	export default {
		onLaunch() {
			_this = this;
			this.getUserInfoByToken();
			getApp().globalData.webSocketConnect = this.webSocketConnect;
		},
		async onShow() {
			uni.$emit('followed');
			this.checkVersion();
			await _this.$loginStatus;
			if (uni.WebIM.conn.logOut || !uni.WebIM.conn.isOpened()) {
				getApp().globalData.webSocketConnect();
			}
		},
		onHide() {
			console.log('App Hide')
		},
		globalData: {

		},
		methods: {
			getUserInfoByToken() {
				//没有token则return,路由首页那边会跳转到登录页的
				if (!this.getTokenSync()) {
					return
				}
				setTimeout(async () => {
					const {
						data
					} = await this.getUserInfo();
					console.log(data);
					//更新用户信息
					this.$u.vuex('userInfo', data);
					console.log("userInfo=>", this.userInfo)
					if (!this.userInfo.customer_type) {
						console.log('没有选身份，跳转到选择身份页面', this.userInfo.customer_type)
						this.$u.route('/pages_login/select_identity/selectIdentity');
					} else if (!this.userInfo.nickname || !this.userInfo.avatars || !this.userInfo.sex) {
						console.log('没有完善用户信息，跳转到完善用户信息页面', this.userInfo)
						this.$u.route('/pages/authentication/authentication');
					} else {
						console.log('登录成功')
						this.$loginResolve();
					}
					const wechat_code = (await wx.login()).code;
					await this.$u.post(this.$restUrl.updateOpenid, {
						phone: data.phone,
						wechat_code,
					})
				}, 200)

			},
			getUserInfo() {
				return this.$u.post(this.$restUrl.getUserInfo);
			},
			async webSocketConnect() {
				console.log('websocket链接')
				console.log(this.userInfo)
				try {
					uni.IM = null;
					uni.IM = new IM({
						userInfo: this.userInfo,
						vm: this
					})
					uni.IM.listen()
					await uni.IM.loginByToken();
					uni.IM.watchLoginState();

					setTimeout(() => {
						uni.IM.setUserInfo();
					}, 2000)
					this.$websocketConnect();
				} catch (e) {
					console.log(e)
				}
			},
			checkVersion() {
				const updateManager = uni.getUpdateManager()
				// 请求完新版本信息的回调
				updateManager.onCheckForUpdate(res => {
					if (res.hasUpdate) {
						// 新版本下载成功
						updateManager.onUpdateReady(() => {
							uni.showModal({
								title: '更新提示',
								content: '新版本已经准备好，点击确定重启小程序',
								success(res) {
									if (res.confirm) {
										// 新的版本已经下载好，强制更新
										updateManager.applyUpdate()
									}
								}
							})
						})
					}
				})
				// 新版本下载失败
				updateManager.onUpdateFailed(res => {
					console.error('小程序版本更新失败>>>>>>>>>>>>>>>>>>>',res);
				})
			}
		}
	}
</script>

<style lang="scss">
	@import "uview-ui/index.scss";
	@import "./static/css/global.css";
	@import "./static/iconfont/iconfont.css";
	@import "./static/iconfont/iconfont-weapp-icon.css";
	@import "./static/css/quill.core.css";
</style>
